package com.zlht.controller;

import com.zlht.entity.Book;
import com.zlht.entity.Warehouse;
import com.zlht.service.BookService;
import com.zlht.service.WarehouseService;
import com.zlht.service.imp.BookServiceImp;
import com.zlht.service.imp.WarehouseServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/warehouse")
public class WarehouseServlet extends HttpServlet {

    WarehouseService warehouseService = new WarehouseServiceImp();
    BookService bookService = new BookServiceImp();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        switch (method) {
            case "list":
                req.setAttribute("list", this.warehouseService.list());
                req.setAttribute("bookList", this.bookService.list());
                req.getRequestDispatcher("warehouseadmin.jsp").forward(req, resp);
                break;
            case "search":
                String key = req.getParameter("key");
                String value = req.getParameter("value");
                req.setAttribute("list", this.bookService.search(key, value));
                req.getRequestDispatcher("warehouseadmin.jsp").forward(req, resp);
                break;
            case "save":
                String name = req.getParameter("name");
                int book_id = Integer.parseInt(req.getParameter("book_id"));
                String address = req.getParameter("address");
                int number = Integer.parseInt(req.getParameter("number"));

                this.warehouseService.save(new Warehouse(name,book_id,address,number));
                resp.sendRedirect("/warehouse?method=list");
                break;
            case "update":
                Integer id = Integer.parseInt(req.getParameter("id"));
                name = req.getParameter("name");
                book_id = Integer.parseInt(req.getParameter("book_id"));
                address = req.getParameter("address");
                number = Integer.parseInt(req.getParameter("number"));


                this.warehouseService.update(new Warehouse(id,name,book_id,address,number));
                resp.sendRedirect("/warehouse?method=list");
                break;
            case "delete":
                id = Integer.parseInt(req.getParameter("id"));
                this.warehouseService.delete(id);
                resp.sendRedirect("/warehouse?method=list");
                break;
        }
    }
}
